﻿ # -*- coding: utf-8 -*-
 
from google.appengine.ext import db
from google.appengine.ext import webapp
from myuser import User
from page import Page
from urlparse import urlparse
import string

class WriteRank(webapp.RequestHandler):
	def get(self):		
		url = self.request.get('url')		
		score = self.request.get('rank')
		callback = self.request.get('callback')	
		
		#parse url to protocol://host:port/path/file
		url_p = urlparse(url)
		
		protocol,domain = url_p[:2]
		back_pos = self.request.get('back_pos')

		
		if url == '' or domain == '' or score == '' or string.atoi(score,10) <= 0 or string.atoi(score,10) >5 :
			self.response.headers['Content-Type'] = 'application/x-javascript'
			self.response.out.write("%s({\"res\":\"err\",\"rank\":\"0\",\"count\":\"0\",\"back_pos\":\"%s\"})" % (callback,back_pos))
			return
				
	    #check user
		user = db.GqlQuery("SELECT * FROM User WHERE domain=:1 ORDER BY date DESC LIMIT 1",domain)		
		#if user absent, create a new user		
		if user.count() < 1:
			user = User()
			user.domain = domain
			user.name = "unknown"
			user.put()					
		else:
			user = user.fetch(1).pop()
			
			
		#match the page url
		page = db.GqlQuery("SELECT * FROM Page WHERE url=:1 ORDER BY date DESC LIMIT 1",url)
		#if page not found , create a new page
		if page.count() < 1:
			page = Page()
			page.url = url
			page.count = 0
			page.score = 0.0
			page.user_id = user.key()
			page.put()
		else:
			page = page.fetch(1).pop()	
		
		page.score = (page.score * page.count + string.atoi(score,10))/(page.count+1)
		page.count = page.count + 1
		page.put()
		
		#return the page rank
		#self.response.out.write('succ&%f&%i' % (page.score , page.count))
		self.response.headers['Content-Type'] = 'application/x-javascript'
		self.response.out.write("%s({\"res\":\"succ\",\"rank\":\"%f\",\"count\":\"%i\",\"back_pos\":\"%s\"})" % (callback,page.score,page.count,back_pos))